package vn.conghuy.talkwithme.responsor.action;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.conghuy.talkwithme.MyApp;
import vn.conghuy.talkwithme.utils.IntWrapper;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class FacebookAction {
	private FacebookAction(){}
	private static FacebookAction instance;
	
	/**
	 * @uml.property  name="context"
	 * @uml.associationEnd  
	 */
	Context context;
	/**
	 * @uml.property  name="appId"
	 */
	String appId;
	/**
	 * @uml.property  name="accessToken"
	 */
	String accessToken;
	/**
	 * @uml.property  name="accessExpires"
	 */
	long accessExpires;
	/**
	 * @uml.property  name="facebook"
	 * @uml.associationEnd  
	 */
	Facebook facebook;
    /**
	 * @uml.property  name="mAsyncRunner"
	 * @uml.associationEnd  
	 */
    AsyncFacebookRunner mAsyncRunner;
    /**
	 * @uml.property  name="mPrefs"
	 * @uml.associationEnd  
	 */
    SharedPreferences mPrefs;
	
	public static FacebookAction getInstance(){
		if(instance == null){
			instance = new FacebookAction();
		}
		return instance;
	}
	
	public void init(String appId, Context context){
		this.appId = appId;
		this.context = context;
		facebook = new Facebook(appId);
		mAsyncRunner = new AsyncFacebookRunner(facebook);
		mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        accessToken = mPrefs.getString("access_token", null);
        accessExpires = mPrefs.getLong("access_expires", 0);
	}
	
	public void logIn(){
		mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        accessToken = mPrefs.getString("access_token", null);
        accessExpires = mPrefs.getLong("access_expires", 0);
        if(accessToken != null) {
            facebook.setAccessToken(accessToken);
        }
        if(accessExpires != 0) {
            facebook.setAccessExpires(accessExpires);
        }
        
        if(!facebook.isSessionValid()) {

        	MyApp myApp = (MyApp)context;
            facebook.authorize(myApp.mainActivity, new String[]{"publish_stream", "manage_notifications"}, new DialogListener() {
                public void onComplete(Bundle values) {
                	accessToken = facebook.getAccessToken();
                    SharedPreferences.Editor editor = mPrefs.edit();
                    editor.putString("access_token", accessToken);
                    editor.putLong("access_expires", facebook.getAccessExpires());
                    editor.commit();
                }
    
                public void onFacebookError(FacebookError error) {}
    
                public void onError(DialogError e) {}
    
                public void onCancel() {}
            });
        }
	}
        
    public boolean updateStatus(String message){
        try {
            Bundle bundle = new Bundle();
            bundle.putString("message", message);
            bundle.putString(Facebook.TOKEN,accessToken);
            String response = facebook.request("me/feed",bundle,"POST");
            if(response != null)
            return true;
            else return false;
        } catch (NullPointerException e) {
			Log.e("NULL POINTER", e.getMessage());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return false;
    }
    
    public ArrayList<String> notifications(IntWrapper sumWrapper){
    	ArrayList<String> notifications = new ArrayList<String>();
   	 	try {
            Bundle bundle = new Bundle();
            bundle.putString(Facebook.TOKEN,accessToken);
            String response = facebook.request("me/notifications",bundle,"GET");
            JSONObject jsonObjectResults = new JSONObject(response);
            JSONArray jsonNotificationDataArray = jsonObjectResults.getJSONArray("data");
            //jsonObjectResults.getInt(name)
            
            JSONObject sumary = jsonObjectResults.getJSONObject("summary");
            int unseen = sumary.getInt("unseen_count");
            if(sumWrapper != null) sumWrapper.setInt(unseen);
            
           	for (int i=0;i<jsonNotificationDataArray.length();i++){
                JSONObject jsonNotificationData = jsonNotificationDataArray.getJSONObject(i);
                notifications.add(jsonNotificationData.getString("title"));
            }
        } catch (MalformedURLException e) {
            Log.e("DEBUG",""+e.getMessage());
        } catch (IOException e) {
            Log.e("DEBUG",""+e.getMessage());
        } catch (JSONException e) {
			e.printStackTrace();
		}
   	 	
   	 	return notifications;
   }
   
   public void logOut(){
   		mAsyncRunner.logout(context, new RequestListener() {

		  public void onComplete(String response, Object state) {}
		  
		  public void onIOException(IOException e, Object state) {}
		  
		  public void onFileNotFoundException(FileNotFoundException e,
		        Object state) {}
		  
		  public void onMalformedURLException(MalformedURLException e,
		        Object state) {}
	
		  public void onFacebookError(FacebookError e, Object state) {}
   		});
   	
   		accessToken = null;
       SharedPreferences.Editor editor = mPrefs.edit();
       editor.putString("access_token", accessToken);
       editor.putLong("access_expires", 0);
       editor.commit();
   }
   
   public boolean isLogin(){
	   if(accessToken == null)
		   return false;
	   else return true;
   }
   
   /**
 * @return
 * @uml.property  name="facebook"
 */
public Facebook getFacebook(){
	   return facebook;
   }
   
   public AsyncFacebookRunner getAsincFacebookRunner(){
	   return mAsyncRunner;
   }

	/**
	 * @return
	 * @uml.property  name="accessToken"
	 */
	public String getAccessToken() {
		return accessToken;
	}
	
	/**
	 * @param accessToken
	 * @uml.property  name="accessToken"
	 */
	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	
	/**
	 * @return
	 * @uml.property  name="accessExpires"
	 */
	public long getAccessExpires() {
		return accessExpires;
	}
	
	/**
	 * @param accessExpires
	 * @uml.property  name="accessExpires"
	 */
	public void setAccessExpires(long accessExpires) {
		this.accessExpires = accessExpires;
	}
   
}
